package com.aopdemo.aspect;

// 以下是所有必要的导入语句，确保全部添加
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Random;

// 标识这是一个切面类
@Aspect
// 标识这是一个Spring组件，让Spring能够扫描到
@Component
public class OrderAspect {

    // 定义切入点：匹配OrderService接口的所有方法
    @Pointcut("execution(* com.aopdemo.service.OrderService.*(..))")
    public void orderServiceMethods() {}

    // 1. 前置增强：所有方法执行前
    @Before("orderServiceMethods()")
    public void beforeAdvice() {
        System.out.println("前置增强: hello, 我是一个前置增强");
    }

    // 2. 后置增强：add和delete方法执行后
    @AfterReturning("execution(* com.aopdemo.service.OrderService.add(..)) || execution(* com.aopdemo.service.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("后置增强: bye, 我是一个后置增强");
    }

    // 3. 获取方法返回值
    @AfterReturning(pointcut = "orderServiceMethods()", returning = "result")
    public void logReturnValue(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        if (result != null) {
            System.out.println("返回值增强: " + methodName + " 方法返回值: " + result);
        } else {
            System.out.println("返回值增强: " + methodName + " 方法无返回值");
        }
    }

    // 4. 计算方法执行时间
    @Around("orderServiceMethods()")
    public Object calculateExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 执行目标方法
        long endTime = System.currentTimeMillis();
        System.out.println("执行时间增强: " + joinPoint.getSignature().getName() +
                " 方法执行时间: " + (endTime - startTime) + "毫秒");
        return result;
    }

    // 5. 权限校验：add和delete方法执行前
    @Before("execution(* com.aopdemo.service.OrderService.add(..)) || execution(* com.aopdemo.service.OrderService.delete(..))")
    public void permissionCheck(JoinPoint joinPoint) {
        Random random = new Random();
        int permission = random.nextInt(2); // 0:有权限, 1:无权限

        String methodName = joinPoint.getSignature().getName();
        if (permission == 0) {
            System.out.println("权限校验: 允许执行 " + methodName + " 方法");
        } else {
            System.out.println("权限校验: 不允许执行 " + methodName + " 方法");
            throw new RuntimeException("权限不足，无法执行 " + methodName + " 方法");
        }
    }
}
    